<template>
  <div>
    <van-nav-bar left-text="返回" title="消息订阅" right-text="新增＋" left-arrow
                 @click-left="$router.go(-1)"
                 @click-right="showPopup = true"/>
    <van-cell-group :style="{ height: `${tableHeight}px` }">
      <van-cell v-for="(item, index) in tableData.datas" :key="index" :title="item.subject">
        <span @click="onDelete(item)" style="color: #ee0a24;cursor: pointer;">
          <van-icon name="delete-o"/>
          <span>删除</span>
        </span>
      </van-cell>
    </van-cell-group>
    <pager v-model="queryParams.page" :total="tableData.total" :limit="queryParams.limit"
           :count="tableData.datas.length" @change="load"/>
    <van-popup v-model="showPopup" position="bottom" :style="{ height: '80%' }">
      <stream-form @close="showPopup= false" @confirm="onCreate"></stream-form>
    </van-popup>
  </div>
</template>

<script>
import {Dialog} from 'vant'

export default {
  components: {
    StreamForm: () => import('@/components/StreamForm.vue'),
    Pager: () => import('@/components/Pager.vue')
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 88
    }
  },
  data() {
    return {
      queryParams: {
        page: 1,
        limit: 20,
        order_by: 'created_at',
        sort_direction: 1
      },
      tableData: {
        total: 0,
        datas: []
      },
      showPopup: false
    }
  },
  methods: {
    load() {
      this.$requests.post('/msg/stream/obtain', this.queryParams).then(resp => {
        this.tableData = resp
      })
    },
    onWechat() {
      this.$requests.post('/msg/wechat/get').then(resp => {
        if (!resp) {
          let uri = `${window.location.protocol}//${window.location.hostname}/wechat`
          this.$requests.post('/msg/wechat/url', {redirect_uri: uri}).then(resp => {
            window.location.href = resp
          })
        }
      })
    },
    onCreate(subject) {
      this.$requests.post('/msg/stream/create', {subject: subject}).then(resp => {
        if (resp) {
          this.showPopup = false
          this.load()
        }
      })
    },
    onDelete(item) {
      Dialog.confirm({
        title: '提示',
        message: `是否删除${item.subject}`,
      }).then(() => {
        this.$requests.post('/msg/stream/delete', {hex_id: item.hex_id}).then(resp => {
          if (resp.n) {
            this.load()
          }
        })
      })
    },
  },
  mounted() {
    this.onWechat()
    this.load()
  }
}
</script>
